<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button :disable="isaddress" type="primary" @click="add()">添加学员</a-button>
          <!-- <a-button :disable="isaddress" type="primary" @click="setaddress = true">批量导入</a-button>
          <a-button :disable="isaddress" type="primary">模版下载</a-button>-->
          <a-button :disable="students.length" type="primary" @click="setaddress2 = true">报班</a-button>
        </a-button-group>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-form :inline="true" size="mini">
          <el-form-item label="学员姓名">
            <el-input v-model="mname" placeholder="学员姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="mphone" placeholder="手机号"></el-input>
          </el-form-item>
          <el-form-item label="校区">
            <el-select v-model="search" placeholder="校区">
              <el-option label="全部校区" value></el-option>
              <el-option
                v-for="(item, i) in getschooladdress"
                :key="`2inline${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
          style="width: 100%; border: 1px solid #eeeeee"
        >
          <el-table-column label="序号" width="60">
            <template slot-scope="scope">
              <input
                type="checkbox"
                name="students"
                :value="scope.row.ID"
                v-model="students"
                :disabled="!(addressid === null || addressid === scope.row.schooladdressid)"
              />
              {{scope.$index+1}}
            </template>>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="80">
            <template slot-scope="scope">
              <router-link
                :to="{name: '学员课程详情', params: { ID: scope.row.ID }}"
                v-text="scope.row.name"
              ></router-link>
            </template>
          </el-table-column>
          <el-table-column sortable prop="sex" label="性别" width="80"></el-table-column>
          <el-table-column sortable prop="birthday" label="出生日期" width="140">
            <template slot-scope="scope">{{ totime(scope.row.birthday)}}</template>
          </el-table-column>
          <el-table-column prop="phonenum" label="手机号"></el-table-column>
          <el-table-column prop="relationship" label="联系人关系"></el-table-column>
          <el-table-column sortable prop="detailedaddress" label="校区">
            <template
              slot-scope="scope"
            >{{ getschooladdressbyid( scope.row.schooladdressid).name}}</template>
          </el-table-column>
          <el-table-column sortable prop="type" label="学员状态"></el-table-column>

          <el-table-column label="操作" align="left" width="250px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="add(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="del(scope.row.ID)">删除</el-button>
              <el-button size="mini" type="warning" @click="state(scope.row)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          @current-change="currentChange"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="tableData.length"
        ></el-pagination>
        <el-dialog class="school-form" :title="title" width="510px" :visible.sync="setaddress">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
            <el-form-item label="学员名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="ruleForm.sex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="出生日期">
              <el-date-picker v-model="ruleForm.birthday" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenum">
              <el-input v-model="ruleForm.phonenum"></el-input>
            </el-form-item>
            <el-form-item label="联系人关系" prop="relationship">
              <el-select
                v-model="ruleForm.relationship"
                filterable
                allow-create
                placeholder="请选择关系"
              >
                <el-option label="母亲" value="母亲"></el-option>
                <el-option label="本人" value="本人"></el-option>
                <el-option label="父亲" value="父亲"></el-option>
                <el-option label="爷爷" value="爷爷"></el-option>
                <el-option label="奶奶" value="奶奶"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择校区" prop="schooladdressid">
              <el-select v-model="ruleForm.schooladdressid" allow-create placeholder="请选择校区">
                <el-option
                  v-for="(item, i) in getschooladdress"
                  :key="`4student${i}`"
                  :label="item.name"
                  :value="item.ID"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学员状态" prop="type">
              <el-radio-group v-model="ruleForm.type">
                <el-radio label="在读"></el-radio>
                <el-radio label="停课"></el-radio>
                <el-radio label="结课"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
            <el-button @click="setaddress = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog class="school-form" title="选择报名班级" width="750px" :visible.sync="setaddress2">
          <el-table :data="clazzbyschooladdresid" style="width: 100%" max-height="250">
            <el-table-column prop="ID" label="序号" width="60">
              <template slot-scope="scope">
                <input type="checkbox" name="clazzs" :value="scope.row.ID" v-model="clazzs" />
                {{scope.$index+1}}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="班级名称"></el-table-column>
            <el-table-column prop="type" sortable label="人数">
              <template
                slot-scope="scope"
              >{{getstudentnum(scope.row.ID)}} / {{ scope.row.studentnum }}</template>
            </el-table-column>
            <el-table-column prop="info" label="所在校区">
              <template
                slot-scope="scope"
              >{{ getschooladdressbyid( scope.row.schooladdressid).name }}</template>
            </el-table-column>
            <el-table-column prop="studentnum" sortable label="课程">
              <template
                slot-scope="scope"
              >{{ scope.row.schoolcourseid?getschoolcoursebyid( scope.row.schoolcourseid).name:'' }}</template>
            </el-table-column>
            <el-table-column prop="type" sortable label="开班日期">
              <template slot-scope="scope">{{ totime(scope.row.starttime) }}</template>
            </el-table-column>
            <el-table-column prop="studentnum" sortable label="结课日期">
              <template slot-scope="scope">{{ totime(scope.row.endtime) }}</template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button
              type="primary"
              size="mini"
              :disabled="addstudentclazz"
              @click="submitForm2"
            >确 定</el-button>
            <el-button @click="setaddress2 = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreateschoolstudent,
  asyncdelschoolstudent,
  asyncresetstudentpassword,
  asyncchangeschoolstudentschoolclazz
} from "../../../../plugins/api.js";
import { totime } from "../../../utils.js";
export default {
  name: "student",
  data() {
    const isphone = (rule, value, callback) => {
      const reg = new RegExp(/^1[3456789]\d{9}$/);
      if (!reg.test(value)) {
        callback(new Error("手机格式不正确"));
      } else {
        callback();
      }
    };
    return {
      mname: "",
      mphone: "",
      isaddress: true,
      setaddress: false,
      setaddress2: false,
      search: "",
      currentPage: 1,
      pagesize: 10,
      title: "添加学员",
      checkList: [],
      resource: true,
      ruleForm: {
        name: "",
        sex: "",
        birthday: "",
        schooladdressid: "",
        ID: "",
        type: "",
        phonenum: "",
        relationship: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        phonenum: [{ required: true, validator: isphone, trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        schooladdressid: [
          { required: true, message: "请选择校区", trigger: "blur" }
        ],
        relationship: [
          { required: true, message: "请选择关系", trigger: "change" }
        ]
      },
      students: [],
      clazzs: [],
      addressid: null,
      addstudentclazz: false
    };
  },
  watch: {
    students(v) {
      if (v.length) {
        this.addressid = this.getschoolstudent.find(
          i => i.ID == v[0]
        ).schooladdressid;
      } else {
        this.addressid = null;
      }
    },
  },
  computed: {
    ...mapGetters([
      "getschoolstudent",
      "getschooladdress",
      "getschoolclazz",
      "getschoolcourse",
      "getschooladdressbyid",
      "getschoolclazzbyid",
      "getschoolcoursebyid"
    ]),
    tableData() {
      const { getschoolstudent, search, mname, mphone } = this;
      return getschoolstudent.filter(data => {
        const x = search ? data.schooladdressid == search : true;
        const y = mname ? data.name.includes(mname) : true;
        const z = mphone ? data.phonenum.toString().includes(mphone) : true;
        return x && y && z;
      });
    },
    clazzbyschooladdresid() {
      const { getschoolclazz } = this;
      return getschoolclazz.filter(v => {
        if (v.type != "0") {
          if (v.schooladdressid === this.addressid || this.addressid === null) {
            return true;
          }
        }
      });
    }
  },
  mounted() {
    if (this.getschooladdress.length) {
      this.isaddress = false;
    }
  },
  methods: {
    totime,
    getstudentnum(id) {
      const { schoolstudentschoolclazz } = this.getschoolclazz.find(
        v => v.ID == id
      );
      return schoolstudentschoolclazz.filter(v => v.type === "在读").length;
    },
    currentChange(index) {
      this.currentPage = index;
    },
    add(v) {
      this.setaddress = true;
      if (v) {
        this.title = "修改学员";
        const {
          ID,
          name,
          sex,
          birthday,
          relationship,
          phonenum,
          type,
          schooladdressid
        } = JSON.parse(JSON.stringify(v));
        this.ruleForm = {
          name,
          sex,
          birthday,
          schooladdressid,
          ID,
          type,
          phonenum,
          relationship
        };
      } else {
        this.title = "添加学员";
        this.ruleForm = {
          name: "",
          sex: "",
          birthday: "",
          schooladdressid: "",
          type: "在读",
          phonenum: "",
          relationship: ""
        };
      }
    },
    del(ID) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger"
      })
        .then(async () => {
          try {
            await asyncdelschoolstudent({ ID });
            await this.$store.dispatch("actionschoolstudent");

            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async state(row) {
      this.$confirm(`是否重置${row.name}密码, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncresetstudentpassword({ ID: row.ID });
            this.$message.success("重置成功");
          } catch (err) {
            this.$message.error(`操作失败：${err}`);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    async submitForm() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.ruleForm.ID ? "修改" : " 添加";
          if (this.resource) {
            this.ruleForm.classscope = "*";
          } else {
            this.ruleForm.classscope = this.checkList.join(",");
          }
          try {
            await asynccreateschoolstudent(this.ruleForm);
            await this.$store.dispatch("actionschoolstudent");
            this.setaddress = false;
            this.$message.success(`${data}成功`);
          } catch (err) {
            this.$message.error(`${data}失败:${err}`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    },
    async submitForm2() {
      if (this.students.length && this.clazzs.length) {
        this.addstudentclazz = true;

        try {
          for (let vo of this.clazzs) {
            const { studentnum, name, ID } = this.getschoolclazz.find(
              v => v.ID == vo
            );
            const num =
              studentnum - this.getstudentnum(ID) - this.students.length;
            if (num < 0) {
              await this.$confirm(
                `${name}班级的人数无法容纳这么多人，超出${-num}人, 是否继续添加?`,
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }
              );
            }
            for (let v of this.students) {
              await asyncchangeschoolstudentschoolclazz({
                schoolclazzid: vo,
                schoolstudentid: v
              });
            }
            await this.$store.dispatch("actionschoolstudent");
          }
          this.$message.success(`添加成功`);
        } catch (err) {
          this.$message.error(`失败:${err}`);
        }
      }
      this.addstudentclazz = false;
      this.setaddress2 = false;
    },
    isclassscope(_rule, _value, callback) {
      if (!this.resource) {
        if (this.checkList.length === 0) {
          callback(new Error("选择了指定校区最少选择一个校区"));
          return;
        }
      }
      callback();
    },
    callin() {}
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.checkbox-group {
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 15px;
  padding-bottom: 15px;
  background-color: #ededed;
}
</style>